﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace AgvPublic
{
    public class UdpManagers
    {
//        public delegate void GetAgvInfo(Model.Agv_Info agvInfo, string ip);
//        public event GetAgvInfo GetAgvInfoEvent;

//        #region Fields

//        // 定义节点
//        private IPEndPoint ipEndPoint = null;
//        private IPEndPoint ChargeEndPoint = null;

//        // 定义AgvUDP发送和接收
//        private UdpClient udpReceive = null;
//        private UdpClient udpSend = null;

//        //定义充电桩Udp发送和接收
//        private UdpClient chargeUdpReceive = null;
//        private UdpClient chargeUdpSend = null;

//        // 定义Agv端口
//        private const int listenPort = 8080;
//        private const int remotePort = 8080;

//        //定义充电桩端口
//        private const int E_listenPort = 8081;
//        private const int E_remotePort = 8080;

//        //Agv接收发送状态类
//        UdpStateModel udpReceiveState = null;
//        UdpStateModel udpSendState = null;

//        //充电桩接收发送状态类
//        UdpStateModel chargeReceiveState = null;
//        UdpStateModel chargeSendState = null;

//        //Agv 异步状态同步
//        private ManualResetEvent sendDone = new ManualResetEvent(false);
//        private ManualResetEvent receiveDone = new ManualResetEvent(false);

//        //ECharge 异步状态同步
//        private ManualResetEvent chargeSendDone = new ManualResetEvent(false);
//        private ManualResetEvent chargeReceiveDone = new ManualResetEvent(false);
//        #endregion

//        #region Ctor

//        /// <summary>
//        /// Udp服务实例化
//        /// </summary>
//        public UdpManagers()
//        {
//            Control.CheckForIllegalCrossThreadCalls = false;
//            // 本机节点
//            ipEndPoint = new IPEndPoint(IPAddress.Any, listenPort);
//            ChargeEndPoint = new IPEndPoint(IPAddress.Any, E_listenPort);
//            // 远程节点

//            // Agv实例化
//            udpReceive = new UdpClient(ipEndPoint);
//            udpReceiveState = new UdpStateModel();
//            udpReceiveState.udpClient = udpReceive;
//            udpReceiveState.ipEndPoint = ipEndPoint;

//            udpSend = new UdpClient();
//            udpSendState = new UdpStateModel();
//            udpSendState.udpClient = udpSend;

//            //Echarge实例化
//            chargeUdpReceive = new UdpClient(ChargeEndPoint);
//            chargeReceiveState = new UdpStateModel();
//            chargeReceiveState.udpClient = chargeUdpReceive;
//            chargeReceiveState.ipEndPoint = ChargeEndPoint;

//            chargeUdpSend = new UdpClient();
//            chargeSendState = new UdpStateModel();
//            chargeSendState.udpClient = chargeUdpSend;

//        }

//        /// <summary>
//        /// AGV接收数据
//        /// </summary>
//        public void ReceiveMsg()
//        {
//            // 调用接收回调函数
//            IAsyncResult iar = udpReceive.BeginReceive(new AsyncCallback(ReceiveCallback), udpReceiveState);
//        }

//        /// <summary>
//        /// 接收充电桩信息
//        /// </summary>
//        //public void ReceiveChargeMsg()
//        //{
//        //    // 调用接收回调函数
//        //    IAsyncResult iar = chargeUdpReceive.BeginReceive(new AsyncCallback(ReceiveChargeCallBack), chargeReceiveState);
//        //}

//        /// <summary>
//        /// 接收充电桩反馈
//        /// </summary>
//        /// <param name="iar">回调函数结果</param>
//        //private void ReceiveChargeCallBack(IAsyncResult iar)
//        //{
//        //    ReceiveChargeMsg();
//        //    UdpStateModel chargeReceiveState = iar.AsyncState as UdpStateModel;
//        //    if (iar.IsCompleted)
//        //    {
//        //        Byte[] receiveBytes = chargeReceiveState.udpClient.EndReceive(iar, ref chargeReceiveState.ipEndPoint);
//        //        if (receiveBytes[4].ToString("x2") == "23")
//        //        {
//        //            List<E_ChargeRecordModel> eModels = E_ChargeRecordLogic.getDataVaild(Model.Share.SqlType.Sql_Type);
//        //            if (eModels == null)
//        //            {
//        //                return;
//        //            }

//        //            E_ChargeRecordModel emodel = new E_ChargeRecordModel();
//        //            emodel.AgvNum = eModels[0].AgvNum;
//        //            //开始充电
//        //            if (eModels[0].BeginTime == "" && receiveBytes[5].ToString("x2") == "01")
//        //            {
//        //                emodel.BeginTime = System.DateTime.Now.ToString("");
//        //                emodel.EndTime = eModels[0].EndTime;
//        //                emodel.E_ChargeFlag = 0;
//        //                E_ChargeRecordLogic.Update(Model.Share.SqlType.Sql_Type,emodel);
//        //            }

//        //            //充电完成
//        //            if (eModels[0].EndTime == "" && receiveBytes[5].ToString("x2") == "02")
//        //            {
//        //                emodel.BeginTime = eModels[0].BeginTime;
//        //                emodel.EndTime = System.DateTime.Now.ToString("");
//        //                emodel.E_ChargeFlag = 1;
//        //                E_ChargeRecordLogic.Update(Model.Share.SqlType.Sql_Type,emodel);
//        //            }
//        //        }
//        //    }
//        //}

//        /// <summary>
//        /// 接收回调函数
//        /// </summary>
//        /// <param name="iar"></param>
//        private void ReceiveCallback(IAsyncResult iar)
//        {
//            try
//            {
//                ReceiveMsg();
//                UdpStateModel udpReceiveState = iar.AsyncState as UdpStateModel;
//                if (iar.IsCompleted)
//                {
//                    //获取小车发送报文
//                    Byte[] receiveBytes = udpReceiveState.udpClient.EndReceive(iar, ref udpReceiveState.ipEndPoint);
//                    string ip = udpReceiveState.ipEndPoint.ToString().Split(':')[0];
//                    //转换成小车信息实体
//                    Model.Agv_Info model = setModel(receiveBytes,ip);
//                    if (model != null)
//                    {
//                        GetAgvInfoEvent(model, ip);
//                    }                      
//                }
//            }
//            catch (Exception ex)
//            {

//            }
//        }

//        /// <summary>
//        /// Agv发送数据1
//        /// </summary>
//        /// <param name="msg">数组</param>
//        public void SendMsg(byte[] msg,string ip)
//        {
          
//            udpSendState.ipEndPoint = new IPEndPoint(IPAddress.Parse(ip), remotePort);
//            udpSend.Connect(udpSendState.ipEndPoint);
//            udpSendState.udpClient = udpSend;
//            udpSendState.counter++;
//            udpSend.BeginSend(msg, msg.Length, new AsyncCallback(SendCallback), udpSendState);
//            // sendDone.WaitOne();
//        }


//        /// <summary>
//        /// 给充电桩发送消息
//        /// </summary>
//        /// <param name="msg">数组</param>
//        public void SendToCharge(byte[] msg)
//        {
//            //string ipAddress = System.Configuration.ConfigurationManager.AppSettings["ChargeIp"];
//            chargeSendState.ipEndPoint = new IPEndPoint(IPAddress.Parse("192.168.31.180"), E_remotePort);
//            chargeUdpSend.Connect(chargeSendState.ipEndPoint);
//            chargeSendState.udpClient = chargeUdpSend;
//            chargeSendState.counter++;
//            chargeUdpSend.BeginSend(msg, msg.Length, new AsyncCallback(SendChargeCallback), udpSendState);
//        }

//        /// <summary>
//        /// 发送充电桩命令反馈
//        /// </summary>
//        /// <param name="iar"></param>
//        private void SendChargeCallback(IAsyncResult iar)
//        {
//            UdpStateModel udpState = iar.AsyncState as UdpStateModel;
//        }

//        /// <summary>
//        /// 发送回调函数
//        /// </summary>
//        /// <param name="iar"></param>
//        private void SendCallback(IAsyncResult iar)
//        {
//            sendDone.Set();
//        }

//        /// <summary>
//        /// 给Agv发送的指令码
//        /// </summary>
//        /// <param name="receiveBytes">Agv接收的数据包</param>
//        /// <returns></returns>
////        internal static AgvMessageModel Send_Agv(Byte[] receiveBytes, UdpStateModel udpReceiveState)
////        {
////            try
////            {
////                //step1  检查有效性
////                if (receiveBytes[0].ToString("x2").ToUpper() != "FD" || receiveBytes[1].ToString("x2").ToUpper() != "10" || receiveBytes[4].ToString("x2") != "31")
////                {
////                    return null;
////                }

////                //step2 发送指令码构造
////                Byte[] SendMsg = receiveBytes;
////                SendMsg[4] = 0x41;
////                List<AgvMessageModel> model = AgvMessageLogic.getAgvMessage(Convert.ToInt16(receiveBytes[14].ToString("x2")));
////                AgvMessageModel Newmodel = setModel(receiveBytes);
////                Newmodel.agvIpAddress = udpReceiveState.ipEndPoint.Address.ToString();

////                //step3 检查读取的点位是否有效
////                bool Isexist = MapPointLogic.IsExist(Newmodel.agvCurrentCard, Model.Share.SqlType.Sql_Type);
////                if (!Isexist)
////                {
////                    return null;
////                }

////                //step4 更新数据库
////                if (model[0].agvCurrentCard != Newmodel.agvCurrentCard || model[0].agvState != Newmodel.agvState || model[0].APan != Newmodel.APan || model[0].BPan != Newmodel.BPan)
////                {
////                    AgvCommunication.AgvStop(Newmodel);//条码停靠站点记录
////                    AgvMessageLogic.AgvUpdate(Newmodel);
////                }
////                return Newmodel;
////            }
////#pragma warning disable CS0168 // 声明了变量“ex”，但从未使用过
////            catch (Exception ex)
////#pragma warning restore CS0168 // 声明了变量“ex”，但从未使用过
////            {
////                return null;
////            }
////        }

//        /// <summary>
//        /// 设置小车信息
//        /// </summary>
//        /// <param name="receiveBytes">Agv接收的数据包</param>
//        /// <returns></returns>
//        internal static Model.Agv_Info setModel(Byte[] receiveBytes,string ip)
//        {
//            Model.Agv_Info agvInfo = new Model.Agv_Info();
//            if (receiveBytes[0].ToString("x2").ToUpper() != "FD" || receiveBytes[1].ToString("x2").ToUpper() != "10" || receiveBytes[3].ToString("x2").ToUpper() != "0F" || receiveBytes[4].ToString("x2").ToUpper() != "31")
//            {
//                return null;
//            }

//            //Model.Agv_Info agvInfo = new Model.Agv_Info();
//            agvInfo.Agv_Num = PublicFunction.GetHexadecimalValue(receiveBytes[14].ToString("x2"));
//            if ((int)receiveBytes[5] == 255)
//            {
//                agvInfo.Agv_Current_Station_Num = 0;
//            }
//            else
//            {
//                agvInfo.Agv_Current_Station_Num = PublicFunction.GetHexadecimalValue(receiveBytes[5].ToString("x2"));
//            }
//            agvInfo.Agv_Speed = PublicFunction.GetHexadecimalValue(receiveBytes[6].ToString("x2"));
//            agvInfo.Agv_Voltage = PublicFunction.GetHexadecimalValue(receiveBytes[7].ToString("x2"));
//            agvInfo.Agv_Distance = PublicFunction.GetHexadecimalValue(receiveBytes[8].ToString("x2"));
//            agvInfo.Agv_Direction = PublicFunction.GetHexadecimalValue(receiveBytes[9].ToString("x2"));
//            agvInfo.Agv_State = PublicFunction.GetHexadecimalValue(receiveBytes[10].ToString("x2"));
//            agvInfo.Agv_Target_Station_Num = PublicFunction.GetHexadecimalValue(receiveBytes[12].ToString("x2"));
//            agvInfo.Agv_Error_Message = PublicFunction.GetHexadecimalValue(receiveBytes[11].ToString("x2"));
//            agvInfo.Agv_Ip_Address = ip;
//            return agvInfo;
//        }

//        /// <summary>
//        /// 托盘信息获取
//        /// </summary>
//        /// <param name="cmdCode">命令码</param>
//        /// <param name="panType">托盘类型</param>
//        /// <returns></returns>
//        public static int AgvPanStatus(int cmdCode, string panType)
//        {
//            switch (cmdCode)
//            {
//                case 0:
//                    {
//                        return 0;
//                    }
//                case 1:
//                    {
//                        if (panType.ToUpper() == "A")
//                        {
//                            return 1;
//                        }
//                        else
//                        {
//                            return 0;
//                        }
//                    }

//                case 2:
//                    {
//                        if (panType.ToUpper() == "B")
//                        {
//                            return 1;
//                        }
//                        else
//                        {
//                            return 0;
//                        }
//                    }

//                case 3:
//                    {
//                        return 1;
//                    }
//            }

//            return 99;
//        }

       

//        #endregion
    }
}
